// pages/square/details/index.js
import {
  wxRequest
} from '../../../utils/server';
const _wxRequest = new wxRequest();
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgList: [],
    dotColor: '#08bb07',
    imgheights: [],
    contentHeight: 0,
    picHeight: 0,
    imgCurrentNum: 0,
    imgInfoOpacity: 0,
    commentTotal: 0,
    isLike: false,
    isCollect: false,
    logType: 1,

    // 作者id
    id: 0,
    vlogList: [],

    // 评论列表
    dataList: [],
    originList: [],
    vlogComment: [],
    pageNo: 1,
    hasNextPage: false,
    init: true,

    isAudit: false,
    auditMsg: ''
  },

  onLoad: function (options) {
    this.data.logId = options?.id
    this.setData({
      isAudit: options.isAudit ? true : false
    })
    this.getList()
  },

  getList() {
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + `/com/protected/vlog/getById`,
      method: 'POST',
      data: {
        id: parseInt(this.data.logId)
      }
    }, (res) => {
      console.log('res', res);
      let vlogList = res?.vo
      if (this.data.init) {
        this.data.logType = res.vo.logType
        console.log(this.data.logType, 'aaaa');

        let imgList = []
        const imgJson = JSON.parse(vlogList.imgJson)
        if (this.data.logType == 1) {
          imgJson.forEach((item, idx) => {
            let img = { url: item.filePath, imgMode: "", ratio: "" }
            imgList.push(img)
          })
          this.handlePic()
        }else{
          vlogList.imgPath = imgJson[0].filePath
        }
        let vlogDate = vlogList.createDate.split(' ')[0]
        this.setData({
          vlogDate,
          imgList: imgList,
          logType: this.data.logType,
          init: false,
          vlogList
        })
      }
      // 获取评论列表
      this.getCommentList()
      this.setData({
        vlogList,
        isLike: res.like,
        isCollect: res.attend,
        likeCommentIdList: res.likeCommentId
      })
    })
  },

  handlePic() {
    setTimeout(() => {
      // 获取评论区上方所有高度，点击后跳转到评论区位置
      // 此操作应该放在接口请求回来后，这里先做测试
      var queryContent = wx.createSelectorQuery();
      queryContent.select('.content').boundingClientRect()
      queryContent.exec((res) => {
        this.data.contentHeight = res[0].height
      })
      var queryPic = wx.createSelectorQuery();
      queryPic.select('.swiper').boundingClientRect()
      queryPic.exec((res) => {
        this.data.picHeight = res[0].height
      })
    }, 1000)
  },


  swiperChange(e) {
    this.setData({
      imgCurrentNum: e.detail.current
    })
  },

  handleSwiperItem() {
    let urls = this.data.imgList.map(item => item.url)
    console.log(urls, urls[this.data.imgCurrentNum]);
    wx.previewImage({
      urls,
      current: urls[this.data.imgCurrentNum]
    })
  },

  imageLoad: function (e) { //获取图片真实宽度
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //宽高比  
      ratio = imgwidth / imgheight;
    //计算的高度值  
    var viewHeight = 750 / ratio;
    var imgheights = this.data.imgheights;
    //把每一张图片的对应的高度记录到数组里  
    imgheights[e.currentTarget.dataset.id] = viewHeight;
    this.data.imgList[e.currentTarget.dataset.id].ratio = ratio
    if (imgheights.length == this.data.imgList.length) {
      imgheights.forEach((item, index) => {
        if (item >= imgheights[0]) {
          if (this.data.imgList[index].ratio > 1) {
            this.data.imgList[index].imgMode = 'widthFix'
          } else {
            this.data.imgList[index].imgMode = 'aspectFit'
          }
        } else {
          if (this.data.imgList[index].ratio >= 1) {
            this.data.imgList[index].imgMode = 'aspectFit'
          } else {
            this.data.imgList[index].imgMode = 'aspectFit'
          }
        }
      })
    }
    this.setData({
      imgheights,
      imgList: this.data.imgList
    })
  },


  /***
   * 评论区
   */
  // 获取数据
  getCommentData(callback, params) {
    let param = params || {
      logId: this.data.logId,
      pageNo: this.data.pageNo,
      hasNextPage: this.data.hasNextPage
    }
    console.log('获取数据', param)
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + `/com/protected/vlogComment/findList`,
      method: 'POST',
      data: param
    }, (res) => {
      res.list.forEach(item => {
        this.data.likeCommentIdList.forEach(i => {
          console.log('item.id,i', item.id, i)
          if (item.id == i) {
            item.commentIsLike = true
          }
        })
      })
      // return
      if (typeof callback == 'function') {
        callback(res)
      }
    })
  },
  // 评论区列表
  getCommentList() {
    let that = this
    this.getCommentData((res) => {
      // 1. 先筛选出评论文章的评论
      res.list = res.list.map(item => {
        item.createDate = item.createDate.split(' ')[0]
        item.children = []
        return item
      }).filter(item => item.pid == 0)

      this.data.vlogComment.forEach((item, index) => {
        res.list.forEach(i => {
          if (item.id == i.id) {
            this.data.vlogComment.splice(index, 1)
          }
        })
      })
      let newVlogComment = this.data.vlogComment.concat(res.list)
      this.setData({
        pageNo: res.page.pageNo,
        hasNextPage: res.page.hasNextPage,
      })
      // 2. 遍历筛选好的评论，若item的评论数大于0，则获取这个评论的id请求该评论下所有的回复
      let ischildren = true
      for (let item of newVlogComment) {
        if (item.replyNum > 0 && item.children.length == 0) {// 回复量
          ischildren = false
          let params = {
            logId: this.data.logId,
            pageNo: this.data.pageNo,
            hasNextPage: this.data.hasNextPage,
            pid: item.id
          }
          this.getCommentData((childrenres) => {
            // 3. 遍历返回回来的数据，把数据塞入到该条评论的chilren数组中
            item.children = item.children.concat(childrenres.list[0])
            console.log('vlogComment - children', res.list);
            this.setData({
              vlogComment: newVlogComment
            })
          }, params)
        }
      }
      if (ischildren) {
        this.setData({
          vlogComment: newVlogComment
        })
      }
    })
  },
  // 展开更多
  handleToShowMoreReply(e) {
    // 点击后传递该评论的id，去查询该评论的所有回复
    let params = {
      logId: this.data.logId,
      pageNo: this.data.pageNo,
      hasNextPage: this.data.hasNextPage,
      pid: e.detail.pid,
      folded: 1
    }
    this.getCommentData((res) => {
      // 1.对原数据进行遍历操作，若发现item的id等于所点击的评论id，则遍历返回会来的数据
      this.data.vlogComment.forEach(item => {
        if (item.id == e.detail.pid) {
          res.list.forEach(i => {
            item.children = item.children.concat(i)
          })
        }
      })
      this.setData({
        vlogComment: this.data.vlogComment,
        pageNo: res.page.pageNo,
        hasNextPage: res.page.hasNextPage,
      })
    }, params)
  },

  // 评论区点赞
  handleClickCommentLike(e) {
    let likeId = e?.detail.likeId
    let isLike = e?.detail.isLike
    let url = isLike ? '/com/protected/vlogComment/thumbsDown' : '/com/protected/vlogComment/thumbsUp'
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + url,
      method: 'POST',
      data: {
        id: likeId
      }
    }, (res) => {
      console.log('res', res);
      var thumbs = (commentList) => {
        for (var i in commentList) {
          if (likeId == commentList[i].id) {
            commentList[i].commentIsLike = !isLike
            commentList[i].likeNum = commentList[i].likeNum * 1
            isLike ? commentList[i].likeNum -= 1 : commentList[i].likeNum += 1
            return commentList
          } else if (commentList[i].children) {
            thumbs(commentList[i].children)
          }
        }
        return commentList
      }
      let newVlogComment = thumbs(this.data.vlogComment)
      this.setData({
        vlogComment: newVlogComment
      })
      //this.getList()
    })
  },

  /***
   * 遮罩层评论
   */

  // 点击点赞图标
  handleClickLike() {
    let url = this.data.isLike ? '/com/protected/vlog/thumbsDown' : '/com/protected/vlog/thumbsUp'
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + url,
      method: 'POST',
      data: {
        id: parseInt(this.data.logId)
      }
    }, (res) => {
      console.log('res', res);
      this.getList()
    })
  },

  // 点击收藏图标
  handleClickCollect() {
    let url = this.data.isCollect ? '/com/protected/vlog/attendDown' : '/com/protected/vlog/attendUp'
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + url,
      method: 'POST',
      data: {
        id: parseInt(this.data.logId)
      }
    }, (res) => {
      console.log('res', res);
      this.getList()
    })
  },

  // 点击评论图标
  handleClickComment() {
    wx.pageScrollTo({
      duration: 300,
      scrollTop: this.data.contentHeight + this.data.picHeight
    })
  },

  // 打开评论输入框
  handleOpenComment(e) {
    console.log('打开输入框', e)
    let replyId = ''
    let replyName = ''
    let parentId = ''
    let userId = ''
    let url = ''
    let param = {}
    let getWrapComponent = this.selectComponent('#wrap')
    if (e.detail.replyId && e.detail.replyName) {
      replyId = e.detail.replyId
      replyName = e.detail.replyName
      parentId = e.detail.parentId
      userId = e.detail.userId
      console.log(parentId, 123123);
      getWrapComponent.editPlaceholder(`回复${replyName}：`)
    } else {
      getWrapComponent.editPlaceholder(`来留下你的评论吧~`)
      replyId = ''
      replyName = ''
    }
    console.log('打开输入框', replyId, replyName, parentId, userId)
    this.setData({
      isFocusInput: true,
      replyId,
      replyName,
      parentId,
      userId
    })
  },

  // 关闭评论输入框
  handleCloseComment(e) {
    this.setData({
      isFocusInput: e.detail.isFocusInput
    })
  },

  getInputVal(e) {
    this.setData({
      inputVal: e.detail.inputVal
    })
  },

  handleSend(e) {
    console.log('发送评论：', e)
    let url = ''
    let params = {}
    let isCreate = false
    if (this.data.replyName !== '' && this.data.replyId !== '') {
      url = '/com/protected/vlogComment/reply'
      isCreate = false
      params = {
        logId: this.data.logId,
        content: this.data.inputVal,
        pid: this.data.parentId == 0 ? this.data.replyId : this.data.parentId,
        replyUserId: this.data.userId, //this.data.replyId,
        replyUserName: this.data.replyName
      }
    } else {
      url = '/com/protected/vlogComment/create'
      isCreate = true
      params = {
        logId: this.data.logId,
        content: this.data.inputVal,
      }
    }
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + url,
      method: 'POST',
      data: params
    }, (res) => {
      console.log('res', res.vo);
      // if (isCreate) {
      //   this.data.vlogComment.concat(res.vo)
      // } else {
      //   this.data.vlogComment.forEach(item => {
      //     // 回复楼主的处理
      //     if (item.id == this.data.replyId && item.id == res.vo.pid) {
      //       console.log('childrem', item.children);
      //       item.children.concat(res.vo)
      //       return
      //     }
      //     // 回复楼中楼的处理
      //     item.children.forEach(i => {
      //       if (i.id == this.data.replyId && i.id == res.vo.pid) {
      //         item.children.concat(res.vo)
      //       }
      //     })
      //   })
      // }
      // console.log('------------------------------------>', this.data.vlogComment);
      //this.getList()
      var addComment = function (vo, commentList) {
        for (var i in commentList) {
          if (vo && vo.pid == commentList[i].id) {
            commentList[i].children.push(vo)
            return commentList
          } else if (commentList[i].children) {
            addComment(vo, commentList[i].children)
          }
        }
        commentList.push(vo)
        return commentList
      }
      let newVlogComment = addComment(res.vo, this.data.vlogComment)
      this.setData({
        vlogComment: newVlogComment
      })
      this.setData({
        isFocusInput: false,
      })
    })
  },

  // 删除评论
  handleToDeleteComment(e) {
    let userId = e.detail.userId
    let replyId = e.detail.replyId
    let url = '/com/protected/vlogComment/deleteReply'
    let params = {
      id: replyId
    }
    if (wx.getStorageSync('userInfo').id == this.data.vlogList.createId || userId == wx.getStorageSync('userInfo').id) {
      wx.showModal({
        content: '确定要删除该回复吗？',
        success: res => {
          if (res.confirm) {
            _wxRequest.wxTonkenAjax({
              url: app.globalData.apiUrl + url,
              method: 'POST',
              data: params
            }, (res) => {
              console.log('res', res);
              this.getList()
            })
          }
        }
      })
    }

  },

  // 审核

  getAuditMsg(e) {
    this.setData({
      auditMsg: e.detail.value
    })
  },

  handleAuditVlog(e) {
    let auditStatus = e.currentTarget.dataset.val
    let url = '/com/protected/vlog/audit'
    let params = {
      auditStatus,
      auditMsg: this.data.auditMsg,
      id: this.data.logId
    }
    if (auditStatus == 1) {
      wx.showModal({
        content: '确定过审这篇笔记吗？',
        success: res => {
          if (res.confirm) {
            _wxRequest.wxTonkenAjax({
              url: app.globalData.apiUrl + url,
              method: 'POST',
              data: params
            }, (res) => {
              console.log('res', res);
              wx.showToast({
                title: '审核通过！',
              })
              wx.navigateBack({
                delta: 1,
              })
            })
          }
        }
      })
    } else {
      if (this.data.auditMsg == '') {
        wx.showToast({
          title: '请填写驳回理由',
          icon: 'none'
        })
        return
      }
      wx.showModal({
        content: '确定驳回这篇笔记吗？',
        success: res => {
          if (res.confirm) {
            _wxRequest.wxTonkenAjax({
              url: app.globalData.apiUrl + url,
              method: 'POST',
              data: params
            }, (res) => {
              console.log('res', res);
              wx.showToast({
                title: '已驳回笔记！',
              })
              wx.navigateBack({
                delta: 1,
              })
            })
          }
        }
      })
    }
  },

  onShow: function () {
  },

  onReady: function () {
    this.videoContext = wx.createVideoContext('myvideo', this);
    this.videoContext.requestFullScreen({ direction: 0 });
  },
  onHide: function () {

  },

  onUnload: function () {

  },

  onReachBottom: function () {
    if (this.data.hasNextPage) {
      this.setData({
        pageNo: this.data.pageNo + 1
      });
      this.getCommentList();
    }

  },

  onShareAppMessage: function () {

  }
})